package com.bw.controller.orders;



import com.bw.entity.material.PiMaterial;

import com.bw.entity.group.OrdergroupEntity;
import com.bw.entity.linkMan.Linkman;
import com.bw.entity.orders.PiOrderLog;
import com.bw.entity.user.TbUser;
import com.bw.req.*;
import com.bw.service.customer.IPiCustomerService;
import com.bw.service.linkman.ILinkmanService;
import com.bw.service.orders.IPiOrderLogService;
import com.bw.service.orders.IPiOrderService;


import com.bw.service.user.ITbUserService;



import com.bw.utils.idwork.IdWorker;
import com.bw.utils.sms.SendSms;
import net.sf.excelutils.ExcelUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bw.entity.customer.PiCustomer;
import com.bw.entity.orders.PiOrder;
import com.bw.resp.ResponseResult;
import com.bw.service.orders.impl.PiOrderServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.InputStream;
import java.util.*;
import java.util.concurrent.TimeUnit;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lizhengqian
 * @since 2020-06-19
 */
@RestController
@RequestMapping("/orders")
public class PiOrderController {
    @Autowired
    private IPiOrderService orderService;
	@Autowired
    private IdWorker idWorker;
	@Autowired
    private ILinkmanService linkmanService;
	@Autowired
    private IPiCustomerService customerService;

	@Autowired
	private ITbUserService userService;

	@Autowired
	private IPiOrderLogService orderLogService;



    private final Logger logger= LoggerFactory.getLogger(PiOrderController.class);

    @GetMapping("getById/{id}")
    public  ResponseResult getOrder(@PathVariable("id") long id){
        ResponseResult result=ResponseResult.SUCCESS();
        logger.info("开始查找单个");
        try {
            result.setResult(this.orderService.getById(id));
        }catch (Exception e){
            logger.error("查找单个失败"+e.toString());
        }
        logger.info("开始查找单个失败");
        return  result;
    }

    /**
     * @Description:
     * @Author: 尹绪瑞
     * @Date: 2020/6/22 20:48
     * @param page:
     * @param size:
     * @param orderForm:
     * @return: com.bw.resp.ResponseResult
     **/
    @PostMapping("list/{page}/{size}")
    public ResponseResult list(@PathVariable("page") int page, @PathVariable("size") int size, @RequestBody OrderForm orderForm) {

        logger.info("查询订单");
        ResponseResult result = ResponseResult.SUCCESS();
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.orderByDesc("updateDate");
        wrapper.eq("isDelete",0);
        try {
            PageHelper.startPage(page, size);

            if (orderForm.getCustomerName() != null && orderForm.getCustomerName()  != "") {
                wrapper.like("customerName","%"+orderForm.getCustomerName()+"%" );
            }
            if (orderForm.getState()!=null){
                wrapper.eq("state",orderForm.getState());
            }

            List<PiOrder> list = orderService.list(wrapper);
            PageInfo pageInfo = new PageInfo(list);
            result.setResult(pageInfo);
            logger.info("查询成功");
        } catch (Exception e) {
            logger.error("查询失败"+e.toString());
            result.setSuccess(false);
            result.setMessage("查询失败" + e.toString());
        }
        logger.info("查询订单结束");
        return result;
    }
    /**
     * @Description:逻辑删除
     * @Author: 尹绪瑞
     * @Date: 2020/6/27 7:36
     * @param id:
     * @return: com.bw.resp.ResponseResult
     **/
    @GetMapping("del/{id}")
    public  ResponseResult del(@PathVariable("id") long id){
        ResponseResult result=ResponseResult.SUCCESS();
        logger.info("开始操作");
        try {
            PiOrder order=orderService.getById(id);
            order.setIsDelete(1);
            order.setUpdateDate(new Date());
            orderService.saveOrUpdate(order);
            logger.info("删除成功");
            result.setMessage("删除成功");
        }catch (Exception e){
            logger.error("删除失败"+e.toString());
            result.setSuccess(false);
            result.setMessage("删除失败"+e.toString());
        }
        logger.info("删除成功结束");
        return  result;
    }
       /**
        * @Description:
        * @Author: 尹绪瑞 
        * @Date: 2020/6/27 7:37
        * @param id: 
        * @param updateId: 
        * @return: com.bw.resp.ResponseResult
        **/
        @GetMapping("find1/{id}/{updateId}")
        public  ResponseResult find(@PathVariable("id") long id,@PathVariable("updateId") long updateId){
          ResponseResult result=ResponseResult.SUCCESS();
          logger.info("开始操作");
          try {
              System.out.println(id);
              PiOrder order=orderService.getById(id);
              order.setState(1);//提交
              order.setUpdateDate(new Date());
              order.setUpdateUser(updateId);
              System.out.println(order);
              orderService.saveOrUpdate(order);
              logger.info("修改成功");
              PiOrderLog piOrderLog = new PiOrderLog();
              piOrderLog.setTbId(order.getTbId());
              piOrderLog.setUserName(userService.getById(order.getTbId()).getUserName());
              piOrderLog.setOrderId(order.getId());
              piOrderLog.setRemarks("提交订单记录");
              orderLogService.save(piOrderLog);
              result.setMessage("修改成功");
          }catch (Exception e){
          logger.error("修改失败"+e.toString());
          result.setSuccess(false);
              result.setMessage("修改失败"+e.toString());
          }
            logger.info("修改结束");
          return  result;
        }
        /**
         * @Description:
         * @Author: 尹绪瑞 
         * @Date: 2020/6/27 7:37
         * @param id: 
         * @param updateId: 
         * @param tid: 
         * @return: com.bw.resp.ResponseResult
         **/
    @PostMapping("find2/{id}/{updateId}/{tid}")
    public  ResponseResult find1(@PathVariable("id") long id,@PathVariable("updateId") long updateId,@PathVariable("tid") long tid){
        ResponseResult result=ResponseResult.SUCCESS();
        logger.info("开始操作");
        try {
            PiOrder order=orderService.getById(id);
            order.setState(2);//转工艺
            order.setTechnicianId(tid);
            order.setTechnologyDate(new Date());
            order.setUpdateDate(new Date());
            System.out.println(order);
            orderService.saveOrUpdate(order);
            order.setUpdateUser(updateId);
            logger.info("修改成功");
            PiOrderLog piOrderLog = new PiOrderLog();
            piOrderLog.setTbId(order.getTbId());
            piOrderLog.setUserName(userService.getById(order.getTbId()).getUserName());
            piOrderLog.setOrderId(order.getId());
            piOrderLog.setRemarks("转工艺订单记录");
            orderLogService.save(piOrderLog);
            result.setMessage("修改成功");
        }catch (Exception e){
            logger.error("修改失败"+e.toString());
            result.setSuccess(false);
            result.setMessage("修改失败"+e.toString());
        }
        logger.info("修改成功");
        return  result;
    }
    /**
     * @Description:
     * @Author: 尹绪瑞 
     * @Date: 2020/6/27 7:37
     * @param id: 
     * @param updateId: 
     * @return: com.bw.resp.ResponseResult
     **/
    @GetMapping("find3/{id}/{updateId}")
    public  ResponseResult find2(@PathVariable("id") long id,@PathVariable("updateId") long updateId){
        ResponseResult result=ResponseResult.SUCCESS();
        logger.info("开始操作");
        try {
            PiOrder order=orderService.getById(id);
            order.setState(3);//转报价
            order.setUpdateDate(new Date());
            order.setUpdateUser(updateId);
            System.out.println(order);
            orderService.saveOrUpdate(order);
            logger.info("修改成功");
            PiOrderLog piOrderLog = new PiOrderLog();
            piOrderLog.setTbId(order.getTbId());
            piOrderLog.setUserName(userService.getById(order.getTbId()).getUserName());
            piOrderLog.setOrderId(order.getId());
            piOrderLog.setRemarks("转报价订单记录");
            orderLogService.save(piOrderLog);
            result.setMessage("修改成功");
        }catch (Exception e){
            result.setSuccess(false);
            logger.error("修改失败"+e.toString());
            result.setMessage("修改失败"+e.toString());
        }
        logger.info("修改成功");
        return  result;
    }
    /**
     * @Description:
     * @Author: 尹绪瑞 
     * @Date: 2020/6/27 7:37
     * @param id: 
     * @param updateId: 
     * @return: com.bw.resp.ResponseResult
     **/
    @GetMapping("find4/{id}/{updateId}")
    public  ResponseResult find3(@PathVariable("id") long id,@PathVariable("updateId") long updateId){
        ResponseResult result=ResponseResult.SUCCESS();
        logger.info("开始操作");
        try {
            PiOrder order=orderService.getById(id);
            order.setState(4);//转合同
            order.setUpdateDate(new Date());
            order.setUpdateUser(updateId);
            System.out.println(order);
            orderService.saveOrUpdate(order);
            logger.info("修改成功");
            PiOrderLog piOrderLog = new PiOrderLog();
            piOrderLog.setTbId(order.getTbId());
            piOrderLog.setUserName(userService.getById(order.getTbId()).getUserName());
            piOrderLog.setOrderId(order.getId());
            piOrderLog.setRemarks("转合同订单记录");
            orderLogService.save(piOrderLog);
            result.setMessage("修改成功");
        }catch (Exception e){
            result.setSuccess(false);
            logger.error("修改失败"+e.toString());
            result.setMessage("修改失败"+e.toString());
        }
        logger.info("修改成功");
        return  result;}



    
    /**
     * @Description:雪花算法产生id
     * @Author: 周明丽
     * @Date: 2020/7/1 19:20
     
     * @return: java.lang.Long
     **/
    @GetMapping("getCode")
    public Long getCodeid(){
        long codeId = idWorker.nextId();
        return codeId;

    }





    /**
     * @Description:保存订单
     * @Author: 周明丽
     * @Date: 2020/7/1 19:20
     * @param entity: 
     * @return: com.bw.resp.ResponseResult
     **/
    @PostMapping("saveOrder")
    public ResponseResult saveOrder(@RequestBody OrdergroupEntity entity){
        ResponseResult result = ResponseResult.SUCCESS();
        try {
           logger.info("开始添加");
            Linkman linkman = linkmanService.getById(entity.getPiOrder().getLinkmanId());
            PiCustomer customer = customerService.getById(entity.getPiOrder().getCustomerId());
            entity.getPiOrder().setCustomerName(customer.getName());
            entity.getPiOrder().setLinkmanName(linkman.getName());
            entity.getPiOrder().setCreateDate(new Date());
            entity.getPiOrder().setUpdateDate(new Date());
            orderService.insertGoup(entity);
            logger.info("添加成功");
            PiOrderLog piOrderLog = new PiOrderLog();
            piOrderLog.setTbId(entity.getPiOrder().getTbId());
            piOrderLog.setUserName(userService.getById(entity.getPiOrder().getTbId()).getUserName());
            piOrderLog.setOrderId(entity.getPiOrder().getId());
            piOrderLog.setRemarks("添加订单");
            orderLogService.save(piOrderLog);
        } catch (Exception e) {
            logger.error("添加失败"+e.toString());
            result.setSuccess(false);
            result.setMessage("添加失败" + e.toString());
        }
        logger.info("添加结束");
        return result;
    }

    /**
     * @Description:导出报价单
     * @Author: 周明丽
     * @Date: 2020/7/1 19:21
     * @param id: 
     * @param response: 
     * @return: com.bw.resp.ResponseResult
     **/
    @GetMapping("getBao/{id}")
    public  ResponseResult getBao(@PathVariable("id") long id, HttpServletResponse response) throws Exception {
        ResponseResult result=ResponseResult.SUCCESS();
        logger.info("开始操作");

        try {
//            response.setHeader("Content-type","application/vnd.ms-excel;charset=UTF-8");
//            response.setHeader("Content-Disposition","attachment;filename="+new String("报价单".getBytes(),"iso-8859-1")+".xls");
            PiOrder order=orderService.getById(id);
            response.setHeader("Content-Type","application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition","attachment;filename="+new String(order.getCode().getBytes(),"iso-8859-1")+".xls");
            orderService.getBao(id,response);
        }catch (Exception e){
            logger.error("导出报价单失败"+e.toString());
            result.setSuccess(false);
            result.setResult("导出报价单失败"+e.toString());
        }
        logger.info("导出结束");
        return result;
    }

    /**
     * @Description:查询
     * @Author: 周明丽
     * @Date: 2020/7/1 19:22
     * @param customerId: 
     * @return: com.bw.resp.ResponseResult
     **/
    @PostMapping("getCusOrders/{customerId}")
    public ResponseResult getCusOrders(@PathVariable("customerId") long customerId){
        ResponseResult result=ResponseResult.SUCCESS();
        QueryWrapper queryWrapper = new QueryWrapper();
        logger.info("查询开始");
        try {
            if(customerId!=0){
                queryWrapper.eq("customerId",customerId);
            }

            queryWrapper.eq("state",3);
            queryWrapper.or();
            queryWrapper.eq("state",4);
            queryWrapper.or();
            queryWrapper.eq("state",5);
            List list = orderService.list(queryWrapper);
            result.setResult(list);
            result.setMessage("查询成功");
        }catch (Exception e){
            logger.error("查询异常"+e.toString());
            result=ResponseResult.FAIL();
            // result.setResult("发送失败"+e.toString());
        }
        logger.info("查询结束");
        return result;
    }



    /**
     * @Description:查询客户订单量
     * @Author: 周明丽
     * @Date: 2020/7/1 19:25

     * @return: com.bw.resp.ResponseResult
     **/
    @PostMapping("cusList")
    public ResponseResult cusList(){
        logger.info("查询开始");
        ResponseResult result=ResponseResult.SUCCESS();

        try {
            List<CusOrder> orderList = orderService.cusList();
            List list1=new ArrayList<>();
            List list2=new ArrayList<>();
            for(CusOrder orderLists:orderList){
                list1.add(orderLists.getCusName());
                list2.add(orderLists.getCusOrder());
            }
            Map map = new HashMap<>();
            map.put("cusName",list1);
            map.put("cusOrder",list2);
            result.setResult(map);
            result.setMessage("查询成功");
        }catch (Exception e){
            logger.error("查询异常"+e.toString());
            result=ResponseResult.FAIL();
            // result.setResult("发送失败"+e.toString());
        }
        logger.info("查询开始");
        return result;
    }


    /**
     * @Description:查询订单金额，订单量
     * @Author: 周明丽
     * @Date: 2020/7/1 19:25

     * @return: com.bw.resp.ResponseResult
     **/
    @PostMapping("cusOrders")
    public ResponseResult cusOrders(){
        logger.info("查询开始");
        ResponseResult result=ResponseResult.SUCCESS();

        try {
            List<CusOrder2> orderList = orderService.ordersList();
            List list1=new ArrayList<>();
            List list2=new ArrayList<>();
            List list3=new ArrayList<>();
            for(CusOrder2 orderLists:orderList){
                list1.add(orderLists.getUpdateDate());
                list2.add(orderLists.getCountOrders());
                list3.add(orderLists.getMoney());
            }
            Map map = new HashMap<>();
            map.put("updateDate",list1);
            map.put("countOrders",list2);
            map.put("money",list3);
            result.setResult(map);
            result.setMessage("查询成功");
        }catch (Exception e){
            logger.error("查询异常"+e.toString());
            result=ResponseResult.FAIL();
            // result.setResult("发送失败"+e.toString());
        }
        logger.info("查询开始");
        return result;
    }


    /**
     * @Description:工艺员工艺订单量
     * @Author: 周明丽
     * @Date: 2020/7/1 19:25

     * @return: com.bw.resp.ResponseResult
     **/
    @PostMapping("gyList")
    public ResponseResult gyList(){
        logger.info("查询开始");
        ResponseResult result=ResponseResult.SUCCESS();

        try {
            List<CusOrder1> orderList = orderService.gyList();
            List list1=new ArrayList<>();
            for(CusOrder1 orderLists:orderList){
                list1.add(orderLists.getName());
            }
            Map map = new HashMap<>();
            map.put("cusName",list1);
            map.put("cusOrder",orderList);
            result.setResult(map);
            result.setMessage("查询成功");
        }catch (Exception e){
            logger.error("查询异常"+e.toString());
            result=ResponseResult.FAIL();
            // result.setResult("发送失败"+e.toString());
        }
        logger.info("查询开始");
        return result;
    }



    /**
     * @Description:查询销售订单量
     * @Author: 周明丽
     * @Date: 2020/7/1 19:25

     * @return: com.bw.resp.ResponseResult
     **/
    @PostMapping("xsList")
    public ResponseResult xsList(){
        logger.info("查询开始");
        ResponseResult result=ResponseResult.SUCCESS();

        try {
            List<CusOrder3> orderList = orderService.xsList();
            List list1=new ArrayList<>();
            for(CusOrder3 orderLists:orderList){
                list1.add(orderLists.getName());
            }
            Map map = new HashMap<>();
            map.put("cusName",list1);
            map.put("cusOrder",orderList);
            result.setResult(map);
            result.setMessage("查询成功");
        }catch (Exception e){
            logger.error("查询异常"+e.toString());
            result=ResponseResult.FAIL();
            // result.setResult("发送失败"+e.toString());
        }
        logger.info("查询开始");
        return result;
    }


}
